package edu.scu.declaresys.dao.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import edu.scu.declaresys.exception.ExecuteException;

public class UpdateHelper<T>
{
	private static HashMap<Class<?>, List<Field>> clzzToFieldsMap = new HashMap<Class<?>, List<Field>>();
	
	private Class<T> clzz;
	
	//
	// Constructors
	//
	public UpdateHelper(Class<T> clzz)
	{
		this.clzz = clzz;
	}
	
	//
	//
	//
	/**
	 * update old object with new object.
	 * @author: zt
	 * @since : 2013-7-2
	 */
	public T update(T oldVo, T vo) throws ExecuteException
	{
		List<Field> fieldLst = null;
		if((fieldLst = clzzToFieldsMap.get(clzz)) != null)
		{
			fieldLst = clzzToFieldsMap.get(clzz);
			for(Field field : fieldLst)
			{
				overWrite(oldVo, vo, field);
			}
			return oldVo;
		}
		// find the field of columns, and cache them.
		fieldLst = new ArrayList<Field>();
		clzzToFieldsMap.put(clzz, fieldLst);
		Field[] fields = clzz.getDeclaredFields();
		Field.setAccessible(fields, true);
		for(Field field : fields)
		{
			Column col = field.getAnnotation(Column.class);
			if(col != null && !col.code().trim().isEmpty())
			{
				fieldLst.add(field);
			}
		}
		return update(oldVo, vo);
	}
	
	/**
	 * update old object's certain field with new object.
	 * @author: zt
	 * @throws ExecuteException 
	 * @since : 2013-7-2
	 */
	private void overWrite(T oldVo, T vo, Field field) throws ExecuteException
	{
		try
		{
			Object obj = field.get(vo);
			if(obj != null)
			{
				field.set(oldVo, obj);
			}			
			return ;
		}
		catch (IllegalArgumentException e)
		{
			throw new ExecuteException(e.getMessage());
		}
		catch (IllegalAccessException e)
		{
			throw new ExecuteException(e.getMessage());
		}
	}
}
